package com.uuah.server.transport.provider.mina;

import java.util.concurrent.Semaphore;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uuah.server.api.IUuahEvent;
import com.uuah.server.api.IUuahMessage;
import com.uuah.server.api.component.IComponent;
import com.uuah.server.api.endpoint.IUuahEndpoint;
import com.uuah.server.api.transport.IConnector;
import com.uuah.server.api.transport.IMessageAdapter;
import com.uuah.server.message.UuahMessage;

/**
 *
 * TODO comment ...
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午02:32:21
 * @version 1.0.0
 */
public class MinaDefalutClientHandler extends IoHandlerAdapter {
	private transient final Logger logger = LoggerFactory
			.getLogger(MinaDefalutClientHandler.class);
	protected final IComponent component;
	protected final IUuahEndpoint endpoint;
	protected final MinaConnector connector;
	protected Object message;
	protected final IUuahEvent sourceEvent;
	private Semaphore lock;

	public MinaDefalutClientHandler(MinaConnector connector,
			IComponent component, IUuahEndpoint endpoint, IUuahEvent sourceEvent,
			Object message, Semaphore lock) {
		this.connector = connector;
		this.component = component;
		this.endpoint = endpoint;

		this.sourceEvent = sourceEvent;

		this.message = message;
		this.lock = lock;
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		super.messageSent(session, message);
		if (logger.isDebugEnabled()) {
			logger.debug("messageSent");
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
		session.write(this.message);

	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		super.messageReceived(session, message);
		if (logger.isDebugEnabled()) {
			logger.debug("messageReceived");
		}

		session.setAttribute(MinaProperties.LAST_MESSAGE_RECEIVED_ATTRIBUTE,
				message);

		IUuahMessage sourceMessage = sourceEvent.getMessage();
		IMessageAdapter adapter = connector.getMessageAdapter(message);
		IUuahMessage newMessage = new UuahMessage(adapter, sourceMessage);

		Number sessionId = sourceMessage.getLongProperty(
				MinaProperties.MINA_SESSION_ID_PROPERTY,
				IConnector.INT_VALUE_NOT_SET);
		newMessage.setLongProperty(MinaProperties.MINA_SESSION_ID_PROPERTY,
				sessionId.longValue());

		this.lock.release();

	}

}
